define(['ionic'], function () {
    var myApp = angular.module('myApp', ['ionic']);
    myApp.run(function () {
        angular.element(document.querySelector('.backdrop')).remove();
        angular.element(document.querySelector('.loading-container')).remove();
        u9.hideLoading();
    });
    myApp.config(function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
        $stateProvider
            .state('home', {
                url: "/home",
                templateUrl: "home.html"
            })
            .state('updatePassword', {
                url: "/updatePassword",
                templateUrl: "updatePassword.html"
            })
            .state('currentMonthDetail', {
                url: "/currentMonthDetail",
                templateUrl: "currentMonthDetail.html"
            });
        $urlRouterProvider.otherwise("/home");

        $ionicConfigProvider.platform.android.navBar.alignTitle('center');
        $ionicConfigProvider.platform.android.backButton.previousTitleText(false);
        $ionicConfigProvider.platform.android.navBar.transition('view');
        $ionicConfigProvider.platform.android.views.transition('ios');
        $ionicConfigProvider.platform.android.views.swipeBackEnabled(true);
        $ionicConfigProvider.platform.android.views.swipeBackHitWidth(45);
        $ionicConfigProvider.platform.android.tabs.style('standard');
        $ionicConfigProvider.platform.android.tabs.position('bottom');
        $ionicConfigProvider.platform.android.form.toggle('large');

        $ionicConfigProvider.platform.default.backButton.previousTitleText(false);
        $ionicConfigProvider.platform.default.backButton.text(false);
    });
    myApp.controller('myController', function ($scope, $state, $ionicLoading, $ionicActionSheet, $ionicModal) {
        var onQuerySalarySuccess;
        var onQuerySalaryError;
        var curYear = new Date().getFullYear();
        var curMonth = new Date().getMonth() == 0 ? 1 : new Date().getMonth(); //default prev month
        var isYear = false; //是否查询年累计
        var isHasPw = true; //用户是否设置了薪资查询密码
        var querySalaryProxyName = "UFIDA.U9.PAY.UMFGetSalaryDataSV.IUMFPayQrySalaryService";
        var queryPasswardProxyName = "UFIDA.U9.PAY.UMFGetSalaryDataSV.IUMFGetEmpQryPWService";
        var updatePasswardProxyName = "UFIDA.U9.PAY.UMFGetSalaryDataSV.IUMFSetEmpQryPWService";
        $scope.curMonth = {
            monthSalary: "0"
        };
        $scope.curYear = {
            yearSalary: "0"
        };
        //查询按钮
        $scope.searchInfo = function (user) {
            if (!user) {
                user = {
                    searchPassword: ""
                }
            }
            isYear = true;
            u9.showLoading();
            $scope.queryPassward(user);
            $scope.doProxy([0, false], queryPasswardProxyName);
        };
        //修改密码---确认按钮
        $scope.affirm = function (passWard) {
            if (!passWard) {
                passWard = {
                    newPassword: "",
                    oldPassword: "",
                    affirmPassword: ""
                }
            }
            if (passWard) {
                if ((passWard.newPassword == passWard.oldPassword) && (passWard.newPassword == "") && (passWard.oldPassword == "")) {
                    u9.alert("请输入密码");
                }
                if (passWard.newPassword == passWard.oldPassword) {
                    u9.alert("新密码与旧密码不能相同");
                } else {
                    if (passWard.newPassword != passWard.affirmPassword) {
                        u9.alert("两次输入的新密码必须相同");
                    } else {
                        u9.showLoading();
                        $scope.updatePassword();
                        $scope.doProxy([passWard.oldPassword, passWard.newPassword, 0, true], updatePasswardProxyName);
                    }
                }
            }
        };
        //找回密码
        $scope.findPassword = function () {
            u9.showLoading();
            onQuerySalarySuccess = function (data) {
                if (data) {
                    u9.alert("查询密码已发送到您的邮箱");
                }
                u9.hideLoading();
            };
            onQuerySalaryError = function (data) {
                u9.alert(data._message);
                u9.hideLoading();
            };
            $scope.doProxy([0, true], queryPasswardProxyName);
        };
        //调用服务方法
        $scope.doProxy = function doProxy(params, proxyName) {
            var jsonData = {
                name: proxyName,
                params: params,
                onSuccess: onQuerySalarySuccess,
                onFailure: onQuerySalaryError
            };
            u9.callSV(jsonData);
        };
        //按月查询成功或失败后调用的方法
        $scope.queryMonthSalary = function (curObj) {
            $scope.dataMonthList = [];
            var obj = curObj; //只给当月工资使用的对象
            onQuerySalarySuccess = function (data) {
                if (data && data.length > 0) { //查月工资返回的数组肯定是一条数据 data[0]
                    var PayCurrency = data[0].PayCurrency; //币种
                    var PayPrecision = parseInt(data[0].PayPrecision); //精度
                    for (var i = 0; i < data[0].SalaryItemList.length; i++) {
                        var result = data[0].SalaryItemList[i];
                        if (obj && result.SalaryItemFieldName == "TotalActPay") { //保存当月实发工资
                            obj.monthSalary = parseFloat(result.SalaryItemValue).toFixed(PayPrecision);
                        }
                        var valueColor = '';
                        var item = 0;
                        if (result.SalaryItemValue) {
                            item = parseFloat(result.SalaryItemValue).toFixed(PayPrecision);
                        }
                        if (result.SalaryItemFieldName != "TaxRate") { //税率字段
                            if (result.ItemAttribute && result.ItemAttribute == 1) { //减项
                                item = '-' + ' ' + PayCurrency + ' ' + item;
                                valueColor = 'valueColor';
                            } else { //加项和其他项
                                item = PayCurrency + ' ' + item;
                            }
                        } else {
                            item = item + "%";
                        }
                        var rowColor = 'basicColor';
                        if ((i + 1) % 2 == 0) { //偶数
                            rowColor = 'evenColor';
                        }
                        $scope.dataMonthList.push({
                            SalaryItemName: result.SalaryItemName,
                            SalaryItemValue: item,
                            RowColor: rowColor,
                            ValueColor: valueColor
                        });
                    }
                } else {
                    $scope.dataMonthList = [];
                    obj.monthSalary = "0";
                }
                if (isYear) { //点击的查询按钮，需要查询月和年工资,异步操作
                    $scope.queryYearSalary($scope.curYear);
                    $scope.doProxy([0, curYear, 0, false], querySalaryProxyName);
                }
                $scope.$apply(); //需要提交一下才能把数据显示到页面上
                if (!isYear) {
                    u9.hideLoading();
                }
                isYear = false;
            };
            onQuerySalaryError = function (data) {
                u9.alert(data._message);
                u9.hideLoading();
            }
        };
        //按年查询成功或失败后调用的方法
        $scope.queryYearSalary = function (curObj) {
            var obj = curObj;
            //查询年度金额的时候先为年度金额指向0
            obj.yearSalary = "0";
            onQuerySalarySuccess = function (data) {
                if (data && data.length > 0) {
                    var PayCurrency = data[0].PayCurrency; //币种
                    var PayPrecision = parseInt(data[0].PayPrecision); //精度
                    for (var i in data) { //先遍历1月到当前月份
                        for (var j in data[i].SalaryItemList) {
                            var result = data[i].SalaryItemList[j];
                            if (obj && result.SalaryItemFieldName == "TotalActPay") {
                                obj.yearSalary = parseFloat(parseFloat(obj.yearSalary) + parseFloat(result.SalaryItemValue)).toFixed(PayPrecision);
                            }
                        }
                    }
                } else {
                    obj.yearSalary = "0";
                }
                $scope.$apply(); //需要提交一下才能把数据显示到页面上
                u9.hideLoading();
            };
            onQuerySalaryError = function (data) {
                u9.alert(data._message);
                obj.yearSalary = "0";
                u9.hideLoading();
            }
        };
        //匹配查询密码
        $scope.queryPassward = function (user) {
            var obj = user;
            onQuerySalarySuccess = function (passWard) {
                if (passWard == 'None PassWord!') {
                    u9.alert("系统中没有您的薪资记录!");
                    u9.hideLoading();
                } else if (passWard == obj.searchPassword) {
                    $scope.CurrentMonth = curYear + "年" + curMonth + "月";
                    $scope.CurrentYear = curYear + "年";
                    $scope.monthTitle = $scope.CurrentMonth + "薪资明细";
                    $scope.monthValue = curMonth + "月";
                    $scope.yearValue = curYear + "年";
                    $state.go("currentMonthDetail");
                    isYear = true; //查询年
                    $scope.queryMonthSalary($scope.curMonth);
                    $scope.doProxy([0, curYear, curMonth, true], querySalaryProxyName);
                } else if (!isHasPw) {
                    u9.alert("您输入的查询密码不正确");
                    u9.hideLoading();
                } else {
                    isHasPw = false;
                }
            };
            onQuerySalaryError = function (passWard) {
                u9.alert(passWard._message);
                u9.hideLoading();
            }
        };
        $scope.queryPassward({searchPassword: ''});
        $scope.doProxy([0, false], queryPasswardProxyName);
        //修改密码
        $scope.updatePassword = function (passWard) {
            var obj = passWard;
            onQuerySalarySuccess = function (isSuccess) {
                if (isSuccess) {
                    u9.alert("修改密码成功");
                    u9.hideLoading();
                    $state.go('home');
                } else {
                    u9.alert("您输入的原密码不正确");
                    u9.hideLoading();
                }
            };
            onQuerySalaryError = function (isSuccess) {
                u9.alert(isSuccess._message);
                u9.hideLoading();
            }
        };
        //前一个月明细按钮
        $scope.prevMonth = function () {
            var date = $scope.CurrentMonth.replace("年", "-").replace("月", "-");
            date = date.split('-');
            var month = parseInt(date[1]);
            var year = parseInt(date[0]);
            month = month - 1;
            if (month <= 0) {
                year -= 1;
                month = 12;
            }
            $scope.queryMSPublic(year, month);
        };
        //下一个月明细按钮
        $scope.nextMonth = function () {
            var date = $scope.CurrentMonth.replace("年", "-").replace("月", "-");
            date = date.split('-');
            var month = parseInt(date[1]);
            var year = parseInt(date[0]);
            month += 1;
            if (month >= 13) {
                year += 1;
                month = 1;
            }
            $scope.queryMSPublic(year, month);
        };
        $scope.date = {
            selectMonth: ''
        };
        //选择任意日期查询工资
        $scope.querySalaryByMonth = function (date) {
            if (date && date.selectMonth) {
                var array = date.selectMonth.split("-");
                var year = array[0];
                var month = array[1];
                $scope.queryMSPublic(year, month);
            }
            $scope.modal.hide();
        };
        //查询月工资公共方法
        $scope.queryMSPublic = function (year, month) {
            $scope.CurrentMonth = year + "年" + month + "月";
            $scope.monthTitle = $scope.CurrentMonth + "薪资明细";
            $scope.monthValue = month + "月";
            if (year != $scope.yearValue.replace("年", "")) {
                $scope.yearValue = year + "年";
                $scope.curYear.yearSalary = 0;
                isYear = true;
                curYear = year;
            }
            u9.showLoading();
            $scope.queryMonthSalary($scope.curMonth);
            $scope.doProxy([0, year, month, false], querySalaryProxyName);
        };

        //Returns from updatePassword
        $scope.upBackHome = function () {
            u9.confirm("请确认是否退出修改密码？").then(function (res) {
                if (res) {
                    $state.go("home");
                }
            });
        };

        $scope.linkToHome = function () {
            var rooturl = localStorage.getItem('rooturl');
            window.location.href = u9.linkToHome('', rooturl);
        };

        $scope.selectdate = function () {
            var curDate = new Date();

            if ($scope.date.selectMonth) {
                var ym = $scope.date.selectMonth.split('-');
                var year = ym[0];
                var month = ym[1] - 1;
                curDate = new Date(year, month, 1);
            }
            var options = {
                date: curDate,
                mode: 'date',
                doneButtonLabel: '确定',
                cancelButtonLabel: "取消"
            };
            u9.plugins.datePicker.show(options, function (date) {
                if (date == 'Invalid Date' || date == 'Nan-Nan') {
                    return;
                }
                $scope.date = {
                    selectMonth: date.getFullYear() + '-' + (date.getMonth() + 1)
                };
                $scope.querySalaryByMonth($scope.date);
                $scope.$apply();
            });
        }
    });
});